package com.paw.security.config;

import com.paw.security.service.DefaultUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author lvzihai
 * @date 2021/7/13
 **/
@Configuration
@ConditionalOnProperty(prefix = "security",name = "type",matchIfMissing = true,havingValue = "web")
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Autowired
  private DefaultUserDetailService userDetailService;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
//        .antMatchers("/", "/index").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .permitAll()
        .and()
        .logout()
        .permitAll();
  }

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    String pwd = passwordEncoder().encode("123456");
    System.out.println("pwd: "+pwd);
    // 内存中用户
//    auth
//        .inMemoryAuthentication()
//        .withUser("admin").password(pwd).roles("USER");

    auth.userDetailsService(userDetailService)
        .passwordEncoder(passwordEncoder());


  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/pub/**");
  }

  @Bean
  @ConditionalOnMissingBean
  public PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
  }


}